package com.yxjx.duoxue.my;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Calendar;

import org.apache.http.client.ClientProtocolException;
import org.codehaus.jackson.mrbean.MrBeanModule;
import org.json.JSONException;
import org.json.JSONObject;

import com.umeng.update.UmengUpdateAgent;
import com.umeng.update.UmengUpdateListener;
import com.umeng.update.UpdateResponse;
import com.umeng.update.UpdateStatus;
import com.yxjx.duoxue.BaseActionBarActivity;
import com.yxjx.duoxue.R;
import com.yxjx.duoxue.R.layout;
import com.yxjx.duoxue.TestActivity;
import com.yxjx.duoxue.TestActivity1;
import com.yxjx.duoxue.Yx;
import com.yxjx.duoxue.ad.AdPageActivity;
import com.yxjx.duoxue.comment.MyCommentsActivity;
import com.yxjx.duoxue.course.HomePageFragment;
import com.yxjx.duoxue.customview.MyProgressDialog;
import com.yxjx.duoxue.dao.Dao;
import com.yxjx.duoxue.global.Globals;
import com.yxjx.duoxue.message.MessageListActivity;
import com.yxjx.duoxue.message.UnreadStatus;
import com.yxjx.duoxue.mta.stat.StatHelper;
import com.yxjx.duoxue.network.NwUtils;
import com.yxjx.duoxue.network.UserLoginResponse;
import com.yxjx.duoxue.network.UserReg;
import com.yxjx.duoxue.payment.ClientUserKidsDTS;
import com.yxjx.duoxue.payment.MyOrderList;
import com.yxjx.duoxue.utils.UIHelper;
import com.yxjx.duoxue.utils.Utils;
import com.yxjx.duoxue.webimage.MainActivity;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class MyPageFragment extends Fragment {
	
	public static final int REQ_CODE_LOGIN_FOR_ACCOUNT = 1;
	public static final int REQ_CODE_LOGIN_FOR_FAVOURITE_COURSES = 2;
	public static final int REQ_CODE_LOGIN_FOR_BOOKED_COURSES = 3;
	public static final int REQ_CODE_LOGIN_FOR_BOOKED_ACTIVITIES = 4;
	public static final int REQ_CODE_MYACCOUNT_FOR_UNLOGIN_OR_EDIT = 5;
	public static final int REQ_CODE_LOGIN_FOR_MY_COMMENTS = 6;
	public static final int REQ_CODE_LOGIN_FOR_MY_ORDER_LIST = 7;
	public static final int REQ_CODE_LOGIN_FOR_MY_COUPON = 8;
	
	private static final int MSG_LOAD_KID_INFO_DONE = 1;


	// cache the fragment view.
	View rootView;
	private Context mContext;
	
	@Override
	public View onCreateView(LayoutInflater inflater,
			@Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
		if (rootView == null) {
			rootView = inflater.inflate(R.layout.fragment_fourth_page, null);
			mContext = rootView.getContext();
			init(rootView);
		} else {
			// used the cached one.
			ViewGroup parent = (ViewGroup) rootView.getParent();
			if (parent != null) {
				parent.removeView(rootView);
			}
		}
		if (Utils.isLogin(mContext)) {
			showLoading(true);
			new Thread(new Runnable() {
				
				@Override
				public void run() {
					JSONObject jo = new JSONObject();
					try {
						jo.put("date", System.currentTimeMillis());
						UserReg.getUserKids(jo, mContext, true);
					} catch (JSONException e) {
						e.printStackTrace();
					} catch (UnsupportedEncodingException e) {
						e.printStackTrace();
					} catch (ClientProtocolException e) {
						e.printStackTrace();
					} catch (IOException e) {
						e.printStackTrace();
					} finally {
						mHandler.sendEmptyMessage(MSG_LOAD_KID_INFO_DONE);
					}
				}
			}).start();
		}
		return rootView;
	}
	
	private Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case MSG_LOAD_KID_INFO_DONE:
				UserLoginResponse ulRsp = UserLoginResponse.getInstance(mContext);
				if (ulRsp != null) {
					updateUIForLoginDone();
				}
				showLoading(false);
				break;
			default:
				break;
			}
		};
	};
	
	private void init(View view) {
		int[] itemIds = new int[] {
			
			R.id.free_audition,
			R.id.my_order_list,
			R.id.reg_activties,
			R.id.my_coupon,
			R.id.score_us,
			R.id.satis_estim,
			R.id.ref_apps,
			R.id.version_update,
			R.id.me_suggestion,
			R.id.about_us
			
		};
		
		int[] itemIdsExtra = new int[] { 
				R.id.has_login, 
				R.id.has_unlogin_btn,
				R.id.my_comments, 
				R.id.favourite_course 
				};
		
		int[] iconIds = new int[] {
				R.drawable.me_listening,
				R.drawable.me_order,
				R.drawable.me_activity,
				R.drawable.me_gift,
				R.drawable.me_grade,
				R.drawable.me_satisfaction,
				R.drawable.me_app,
				R.drawable.me_update,
				R.drawable.me_suggestion,
				R.drawable.me_about
		};
		
		String[] titles = getResources().getStringArray(R.array.setting_items);
		for (int i = 0; i < itemIds.length; i++) {
			UIHelper.setText(view, itemIds[i], R.id.title, titles[i]);
			UIHelper.setDrawable(view.findViewById(itemIds[i]), R.id.indicator, iconIds[i]);
		}
		
		for (int id : itemIds) {
			UIHelper.setClickListener(view, id, mClickListener);
		}
		for (int id: itemIdsExtra) {
			UIHelper.setClickListener(view, id, mClickListener);
		}
		
		// 显示手机号码
		updateHeadAsLogin(Utils.isLogin(mContext));
		
		/// 某些渠道不希望出现应用推荐这一栏。
		String[] blackChannels = new String[] {
				"anzhi",
				"nduo",
		};
		String curChannel = Utils.getChannelCode(mContext);
		for (String item : blackChannels) {
			if (curChannel.endsWith(item)) {
				view.findViewById(R.id.ref_apps).setVisibility(View.GONE);
				view.findViewById(R.id.ref_apps_divider).setVisibility(View.GONE);
			}
		}
		///
		
	}
	
	private View.OnClickListener mClickListener = new View.OnClickListener() {
		
		@Override
		public void onClick(View arg0) {
			StatHelper.addKVEvent(mContext, "event_my_tab_click");
			switch (arg0.getId()) {
			case R.id.about_us:
				startActivity(new Intent(mContext, AboutUsActivity.class));
				break;
			case R.id.has_login:
			case R.id.has_unlogin_btn:
				viewAccount(arg0);
				break;
			case R.id.my_coupon:
				StatHelper.addKVEvent(mContext, "event_my_coupon_click");
				if (UserLoginResponse.getInstance(mContext) != null) {
					startMyCouponInternal(mContext);
				} else {
					startActivityForResult(new Intent(mContext,
							UserLoginActivity.class),
							REQ_CODE_LOGIN_FOR_MY_COUPON);
				}
				break;
			case R.id.ref_apps:
				StatHelper.addKVEvent(mContext, "event_my_app_click");
				startActivity(new Intent(mContext, AppRefActivity.class));
				break;
			case R.id.free_audition:
				StatHelper.addKVEvent(mContext, "event_my_course_click");
				if (UserLoginResponse.getInstance(mContext) != null) {
					startActivity(new Intent(mContext, AppointedCourses.class));
				} else {
					startActivityForResult(new Intent(mContext,
							UserLoginActivity.class),
							REQ_CODE_LOGIN_FOR_BOOKED_COURSES);
				}
				break;
			case R.id.my_order_list:
				if (UserLoginResponse.getInstance(mContext) != null) {
					startActivity(new Intent(mContext, MyOrderList.class));
				} else {
					startActivityForResult(new Intent(mContext,
							UserLoginActivity.class),
							REQ_CODE_LOGIN_FOR_MY_ORDER_LIST);
				}
				break;
			case R.id.favourite_course:
				viewFavouriteCourses(arg0);
				break;
			case R.id.reg_activties:
				StatHelper.addKVEvent(mContext, "event_my_activity_click");
				if (UserLoginResponse.getInstance(mContext) != null) {
					startActivity(new Intent(mContext, RegisteredActivitiesPage.class));
				} else {
					startActivityForResult(new Intent(mContext,
							UserLoginActivity.class),
							REQ_CODE_LOGIN_FOR_BOOKED_ACTIVITIES);
				}
				break;
			case R.id.my_comments:
				viewMyComment(arg0);
				break;
			case R.id.score_us:
				Utils.leadUserToRatingInMarket(mContext);
				break;
			case R.id.satis_estim:
				startActivity(new Intent(mContext, SatisficationEstimationActivity.class));
				break;
			case R.id.version_update:
				checkNewVersion(mContext);
				// 测试 web cache image
//				startActivity(new Intent(getActivity(), MainActivity.class));
				break;
			case R.id.me_suggestion:
				StatHelper.addKVEvent(mContext, "event_my_feedback_click");
				startActivity(new Intent(mContext, FeedbackActivity.class));
				break;
			default:
				break;
			}
		}

	};
	
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (requestCode) {
		case REQ_CODE_LOGIN_FOR_ACCOUNT:
			if (resultCode == Activity.RESULT_OK) {
				updateUIForLoginDone();
				startMyAccountForResult();
			}
			break;
		case REQ_CODE_LOGIN_FOR_FAVOURITE_COURSES:
			if (resultCode == Activity.RESULT_OK) {
				updateUIForLoginDone();
				startActivity(new Intent(mContext, FavouriteCoursesActivity.class));
			}
			break;
		case REQ_CODE_LOGIN_FOR_BOOKED_COURSES:
			if (resultCode == Activity.RESULT_OK) {
				updateUIForLoginDone();
				startActivity(new Intent(mContext, AppointedCourses.class));
			}
			break;
		case REQ_CODE_LOGIN_FOR_MY_ORDER_LIST:
			if (resultCode == Activity.RESULT_OK) {
				updateUIForLoginDone();
				startActivity(new Intent(mContext, MyOrderList.class));
			}
			break; 
		case REQ_CODE_LOGIN_FOR_BOOKED_ACTIVITIES:
			if (resultCode == Activity.RESULT_OK) {
				updateUIForLoginDone();
				startActivity(new Intent(mContext,
						RegisteredActivitiesPage.class));
			}
			break;
		case REQ_CODE_MYACCOUNT_FOR_UNLOGIN_OR_EDIT:
			if (resultCode == Activity.RESULT_OK) {
				updateUIForUnloginDone();
			} else if (resultCode == Activity.RESULT_CANCELED) {
				updateUIForLoginDone();
			}
			break;
		case REQ_CODE_LOGIN_FOR_MY_COMMENTS:
			if (resultCode == Activity.RESULT_OK) {
				updateUIForLoginDone();
				startActivity(new Intent(mContext,
						MyCommentsActivity.class));
			}
			break;
		case REQ_CODE_LOGIN_FOR_MY_COUPON:
			if (resultCode == Activity.RESULT_OK) {
				updateUIForLoginDone();
				startMyCouponInternal(mContext);
			}
			break;
		default:
			break;
		}
	}

	private void updateUIForUnloginDone() {
		// TODO: update UI as unloggin status.a) 隐藏号码，b) actionbar登录
		updateHeadAsLogin(false);
	}
	
	private void updateUIForLoginDone() {
		// TODO: update UI as login status.a) 显示号码，b) actionbar已登录
		updateHeadAsLogin(true);
	}

	private void startMyAccountForResult() {
		startActivityForResult(new Intent(mContext, MyAccountActivity.class), REQ_CODE_MYACCOUNT_FOR_UNLOGIN_OR_EDIT);
	};
	
	private void checkNewVersion(final Context context) {
		
		final ProgressDialog progressDialog = MyProgressDialog.show(mContext, "", "正在检查更新，请稍后");
		progressDialog.setCancelable(false);
		UmengUpdateAgent.setUpdateAutoPopup(false);
		UmengUpdateAgent.setUpdateOnlyWifi(false);
		UmengUpdateAgent.setUpdateListener(new UmengUpdateListener() {

			@Override
			public void onUpdateReturned(int updateStatus, UpdateResponse updateInfo) {
				switch (updateStatus) {
		        case UpdateStatus.Yes: // has update
		        case UpdateStatus.NoneWifi: // none wifi
		            UmengUpdateAgent.showUpdateDialog(context, updateInfo);
		            break;
		        case UpdateStatus.No: // has no update
		            Toast.makeText(context, "已经是最新版本", Toast.LENGTH_SHORT).show();
		            break;
		        case UpdateStatus.Timeout: // time out
		            Toast.makeText(context, "请求超时", Toast.LENGTH_SHORT).show();
		            break;
		        }
				// reset configuration.
				progressDialog.dismiss();
				UmengUpdateAgent.setUpdateAutoPopup(true);
				UmengUpdateAgent.setUpdateListener(null);
				
			}
		});
		UmengUpdateAgent.update(context);
	}
	
	public void viewAccount(View view) {
		if (UserLoginResponse.getInstance(mContext) != null) {
			startMyAccountForResult();
		} else {
			startActivityForResult(new Intent(mContext,
					UserLoginActivity.class),
					REQ_CODE_LOGIN_FOR_ACCOUNT);
		}
	}

	public void viewMyComment(View view) {
		if (UserLoginResponse.getInstance(mContext) != null) {
			startActivity(new Intent(mContext, MyCommentsActivity.class));
		} else {
			startActivityForResult(new Intent(mContext,
					UserLoginActivity.class),
					REQ_CODE_LOGIN_FOR_MY_COMMENTS);
		}
	}
	
	public void viewFavouriteCourses(View view) {
		if (UserLoginResponse.getInstance(mContext) != null) {
			startActivity(new Intent(mContext, FavouriteCoursesActivity.class));
		} else {
			startActivityForResult(new Intent(mContext,
					UserLoginActivity.class),
					REQ_CODE_LOGIN_FOR_FAVOURITE_COURSES);
		}
	}
	
	private void updateHeadAsLogin(boolean isLogin) {
		View head = rootView.findViewById(R.id.me_head);
		// fragment的生命周期导致此时View没有被初始化。
		if (head == null) {
			return;
		}
		View login = head.findViewById(R.id.has_login);
		View unlogin = head.findViewById(R.id.has_unlogin);
		if (isLogin) {
			String phone = Utils.getValueFromSharedPreference(mContext, Yx.KEY_PHONE_NUM);
			login.setVisibility(View.VISIBLE);
			unlogin.setVisibility(View.INVISIBLE);
			UIHelper.setText(login, R.id.phone_num, "账号：" + phone);
			UIHelper.setText(login, R.id.child_info, getChildDes());
			
		} else {
			login.setVisibility(View.INVISIBLE);
			unlogin.setVisibility(View.VISIBLE);
		}
	}
	
	private String getChildDes() {
		ClientUserKidsDTS kidInfo = Dao.getUserKidInfo(mContext);
		if (kidInfo != null) {
			return "学生：" + kidInfo.getKidsName() + " " + getKidDetail(kidInfo);
		}
		return "学生：暂无学生信息";
	}
	
	public static String getKidDetail(ClientUserKidsDTS kidInfo) {
		if (kidInfo == null) {
			return "";
		}
		return "（" + (kidInfo.getKidsSex() == 1 ? "男孩" : "女孩") + "，"
				+ Utils.getAgeDesc(kidInfo) + "）";
	}
	
	private static void startMyCouponInternal(Context context) {
		if (!Utils.isLogin(context)) {
			return;
		}
		
		Intent intent = new Intent(context, AdPageActivity.class);
		intent.putExtra(Yx.KEY_TITLE, "我的代金券");
		intent.putExtra(Yx.KEY_URL, NwUtils.URL_MY_COUPON + UserLoginResponse.getInstance(context).getSid()
				+ NwUtils.webTail());
		context.startActivity(intent);
	}
	
	/**
	 * 启动我的优惠劵页面
	 * @param context
	 */
	public static void startMyCoupon(Context context) {
		startMyCouponInternal(context);
	}
	
	public void showMessageList(View view) {
		startActivity(new Intent(view.getContext(), MessageListActivity.class));
	}
	
	private void tryUpdateActionBar() {
		HomePageFragment.tryUpdateActionBarInternal(getActivity(), R.id.messages);
	}
	
	@Override
	public void onResume() {
		super.onResume();
		tryUpdateActionBar();
	}
	
	private void showLoading(boolean loading) {
		rootView.findViewById(R.id.scroll).setVisibility(loading ? View.INVISIBLE : View.VISIBLE);
		rootView.findViewById(R.id.loading).setVisibility(loading ? View.VISIBLE : View.INVISIBLE);
	}
}
